package com.gxa.servlet.goods;

import com.alibaba.fastjson.JSON;
import com.gxa.pojo.Result;
import com.gxa.pojo.goods.Goods;
import com.gxa.pojo.goods.Goods1;
import com.gxa.pojo.goods.GoodsPage;
import com.gxa.service.goods.GoodsService;
import com.gxa.service.goods.impl.GoodsServiceimpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/GoodsPageServlet")
public class GoodsPageServlet extends HttpServlet {
    GoodsService goodsService = new GoodsServiceimpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String begin = request.getParameter("page");
        String size = request.getParameter("size");
        int start = Integer.parseInt(begin);
        int size1 = Integer.parseInt(size);
        BufferedReader reader = request.getReader();
        StringBuilder stringBuilder = new StringBuilder();
        String sr;
        while ((sr=reader.readLine())!=null){
            stringBuilder.append(sr);
        }
        String s = stringBuilder.toString();
        int i = goodsService.selectAllPage();
        Goods goods = JSON.parseObject(s, Goods.class);
        List<Goods1> goods1 = goodsService.selectByPageAndif(start, size1, goods);
        GoodsPage<Goods1> goodsPage = new GoodsPage<>();
        goodsPage.setRows(goods1);
        goodsPage.setAllconut(i);
        Map<String, Object> map = new HashMap<>();
        if (i!=0&&goods1!=null ) {
            map.put("Result", Result.ok("查询成功",goodsPage));
        }else {
            map.put("Result",Result.error());
        }
        String s1 = JSON.toJSONString(map);
        response.setContentType("text/Json;charset=utf-8");
        response.getWriter().write(s1);


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
